package com.xwaf.platform.web.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;
import org.springframework.web.filter.DelegatingFilterProxy;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;

import com.xwaf.platform.common.web.config.WebConfig;
import com.xwaf.platform.system.api.service.gateway.CurrentLimitService;
import com.xwaf.platform.web.filter.CurrentLimitRequiredInterceptor;

@Configuration
public class FilterConfig extends WebConfig {

	private static final String[] ALL_PATH_PATTERNS = { "/**" };

	@Autowired
	private CurrentLimitRequiredInterceptor currentLimitRequiredInterceptor;

	@Bean
	@DependsOn("currentLimitService")
	public CurrentLimitRequiredInterceptor currentLimitRequiredInterceptor(CurrentLimitService currentLimitServ) {
		return new CurrentLimitRequiredInterceptor(currentLimitServ);
	}

	@Override
	public void addInterceptors(InterceptorRegistry registry) {
		registry.addInterceptor(currentLimitRequiredInterceptor).addPathPatterns(ALL_PATH_PATTERNS);
		logger.info("added {} for path patterns: {}", currentLimitRequiredInterceptor, ALL_PATH_PATTERNS);
		super.addInterceptors(registry);
	}

	@Bean
	public FilterRegistrationBean shiroFilterRegistration() {
		FilterRegistrationBean registration = new FilterRegistrationBean();
		registration.setFilter(new DelegatingFilterProxy("shiroFilter"));
		// 该值缺省为false，表示生命周期由SpringApplicationContext管理，设置为true则表示由ServletContainer管理
		registration.addInitParameter("targetFilterLifecycle", "true");
		registration.setEnabled(true);
		registration.setOrder(Integer.MAX_VALUE - 1);
		registration.addUrlPatterns("/*");
		return registration;
	}
}
